<template>
	<view class="content" style="height: 100vh;">
		<u-form :model="userInfo" ref="form1" class="user-list list-border">
			<view class="" style="display: flex;">
				<view class="" style="display: flex;margin-top:50rpx;width: 100%;">
					<view class="" style="width: 30%; ">
						<image :src="userInfo.TJMainImg" class="image" mode="" style="height: 80px;width:80px;">
						</image>
					</view>
					<view class=""
						style="width:70%;font-weight: bold;display: flex;align-items: center;justify-content: center;">
						体检项目:{{userInfo.TJName}}
					</view>

				</view>
			</view>

			<u-form-item label="体检人" label-width="150">
				<view class="boldtext">
					{{userInfo.TJNName}}
				</view>
			</u-form-item>
			<u-form-item label="体检费用" label-width="150">
				<view class="boldtext">
					{{userInfo.TJPrice}}
				</view>

			</u-form-item>
			<u-form-item label="体检日期" label-width="150">
				<view>

					<u-calendar :holidays="jiejiari" formatter="formatter" max-date="2050-01-01" :min-date="currentData"
						v-model="show" :mode="mode" @change="change" btn-type="default"
						:disabled-date="disableWeekends"></u-calendar>
					<view @click="show = true" style="text-align: left;font-weight: bold;">{{this.Date}}</view>
				</view>
			</u-form-item>
			<u-form-item label="可预约人数" label-width="150">
				<view class="boldtext">
					{{this.people}}
				</view>
			</u-form-item>

		</u-form>
		<view class="bottom-button">
			<view class="button bacnone2" @click="pay()">提交</view>
		</view>

		<u-modal v-model="showPay" confirm-color='#0197F6' :content="content4" show-cancel-button="true"
			@confirm="ComPay()" @cancel="showPay = false" mask-close-able="true"></u-modal>

		<u-modal v-model="showtishi" confirm-color='#0197F6' :content="content" @confirm="showtishi = false"></u-modal>
		<u-modal v-model="showtishi2" confirm-color='#0197F6' :content="content2"
			@confirm="showtishi2 = false"></u-modal>
		<u-modal v-model="showtishi3" confirm-color='#0197F6' :content="content3" :mask-close-able="false"
			@confirm="tomain()"></u-modal>
		<!-- <u-popup v-model="showPay" mode="center" border-radius="14" width="400rpx" height="100px"
			:mask-closable="false">
			<view class="" style="padding: 10px;">
				<view class="" style="text-align: center;height:50px;">
					确认是否支付?
				</view>
				<view class="" style="display: flex;justify-content: center;">
					<view class="" style="text-align: left;width: 50%;">
						<u-button class="custom-style" :ripple="true" :hair-line="false" size="mini"
							@click="showPay = false">取消支付</u-button>
					</view>
					<view  class="custom-style" style="text-align: right;width: 50%;">
						<u-button type="info" :ripple="true" :hair-line="false" size="mini"
							@click="ComPay()">确认支付</u-button>
					</view>
				</view>


			</view>

		</u-popup> -->


	</view>
</template>

<script>
	import {
		mapState,
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {

				showCalendar: false,
				mode: 'date',
				selectedDate: '',
				minDate: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30天前
				maxDate: Date.now() + 180 * 24 * 60 * 60 * 1000, // 180天后

				// 2025年节假日示例（实际使用时需更新）
				jiejiari: [

				],
				tempday: [

				],
				currentData: new Date().toISOString().split("T")[0],
				content4: '是否进行提交?',
				show: false,
				mode: 'date',
				Date: '请选择日期',
				people: '100',
				DotDate: [],
				showPay: false,
				content: '日期已被预约！',
				content2: '请选择日期！',
				content3: '预约成功！',
				showtishi: false,
				showtishi2: false,
				showtishi3: false,
				userInfo: {
					TJTestId: '',
					TJName: '',
					TJPrice: '',
					TJChildId: '',
					TJName: '',
					TJNName: '',
					OrderNo: '',
					TJMainImg: '',
				},

				select1: {
					show: false,
					current: {},
					list: [{
							value: 1,
							label: '男'
						},
						{
							value: 2,
							label: '女'
						}
					],
				},
				selectCase: {
					show: false,
					current: {},
					list: [],
				},
				selectGrade: {
					show: false,
					current: {},
					list: [],
				},
				selectKinder: {
					show: false,
					current: {},
					list: [],
				},
				useyzm: '',
				rules: {
					Kinder: [{
						required: true,
						message: '请选择幼儿园',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}],

					TJName: [{
						required: true,
						message: '请输入姓名',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}],
					TJPName: [{
						required: true,
						message: '请输入姓名',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}],
					His: [{
						required: true,
						message: '请输入姓名',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}],
					TJAddress: [{
						required: true,
						message: '请输入姓名',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}],
					sex: [{
						required: true,
						message: '请选择性别',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}],
					TJIDCardNo: [{
							required: true,
							message: '请输入身份证',
							// 可以单个或者同时写两个触发验证方式
							trigger: 'blur,change'
						},
						{
							len: 18,
							message: '请正确输入18位身份证',
							// 可以单个或者同时写两个触发验证方式
							trigger: 'blur,change'
						}
					],

					TJPIDCard: [{
							required: true,
							message: '请输入家长姓名',
							// 可以单个或者同时写两个触发验证方式
							trigger: 'blur,change'
						},
						{
							len: 18,
							message: '请正确输入18位身份证',
							// 可以单个或者同时写两个触发验证方式
							trigger: 'blur,change'
						}
					],
					TJPhoneNo: [{
							required: true,
							message: '请输入就诊人手机号',
							// 可以单个或者同时写两个触发验证方式
							trigger: 'blur,change'
						},
						{
							len: 11,
							message: '请正确输入11位手机号',
							// 可以单个或者同时写两个触发验证方式
							trigger: 'blur,change'
						}
					]
				},
			}
		},
		watch: {
			value(newValue, oldValue) {
				//console.log('v-model', newValue);
			}
		},
		computed: {
			...mapState(['token'], ['userInfo']),
			...mapGetters(['hasLogin', 'getUserInfo']),
			getIcon() {
				return path => {
					return 'https://cdn.uviewui.com/uview/example/' + path + '.png';
				}
			}
		},
		onLoad(options) {
			console.log("开始了++++++++++++++++++")
			console.log(options)
			if (options.TJTestId != undefined) {
				this.userInfo.TJChildId = options.TJChildId;
				this.userInfo.TJNName = options.TJNName;
				this.userInfo.TJTestId = options.TJTestId;
				console.log("刚开始加载" + options.TJTestId)




				uni.hideLoading();

			}


		


		},
		async created() {
			// 直接调用异步方法并赋值
			this.tempday = await this.getYearHolidays(new Date().getFullYear())

			// 处理数据
			this.jiejiari = this.tempday.map(item => item.date);

			// 现在可以在模板中使用 holidayDates
			console.log('主线程获取到的节假日:', this.jiejiari);
		},
		// onBackPress(event) {
		// 	uni.switchTab({
		// 		url: '/pages/index/index'
		// 	});
		// 	return true;
		// },

		onShow() {
			if (this.hasLogin) {
				uni.showLoading({
					title: '加载中'
				})
				this.$store.dispatch('getUserInfo');
				this.getlist()
				//this.getDate()
			} else {
				uni.hideLoading();
				uni.showModal({
					title: '提示',
					content: '登录后才可以操作',
					confirmText: '去登录',
					showCancel: false,
					success: function(res) {
						uni.reLaunch({
							url: '/pages/auth/login'
						})
					}
				});
				return;
			}

		},

		onReady() {
			this.$refs.form1.setRules(this.rules);
		},

		// created() {
		// 	this.getKinder();
		// 	this.getCase();
		// 	this.getGrade();
		// },

		methods: {
			// 获取整年节假日
			async getYearHolidays(year) {
				try {
					const res = await uni.request({
						url: `https://timor.tech/api/holiday/year/${year}`,
						method: 'GET'
					});

					if (res.statusCode === 200) {
						const holidays = [];
						const data = res.data;

						if (data.code === 0 && data.holiday) {
							// 遍历所有节假日
							for (const date in data.holiday) {
								const holidayInfo = data.holiday[date];

								// 只收集放假的日子
								if (holidayInfo.holiday) {
									holidays.push({
										date: holidayInfo.date,
										name: holidayInfo.name,
										isHoliday: holidayInfo.holiday,
										wage: holidayInfo.wage
									});
								}
							}
						}
						console.log(holidays)
						return holidays

					} else {
						console.error('获取节假日失败', res);
						return [];
					}
				} catch (error) {
					console.error('请求节假日API出错', error);
					return [];
				}
			},

			disabledDate(date) {
				const dateObj = new Date(date.timestamp);

				// 1. 禁用周末（周六=6, 周日=0）
				const day = dateObj.getDay();
				if (day === 0 || day === 6) return true;

				// 2. 禁用节假日
				const dateStr = this.formatDate(dateObj);
				return this.jiejiari.includes(dateStr);
			},

			// 日期格式化 YYYY-MM-DD
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 确认选择
			confirm(e) {
				this.selectedDate = this.formatDate(new Date(e[0]));
				this.showCalendar = false;
			},
			// 自定义日期格式化
			formatter(day) {
				const d = new Date()
				let month = d.getMonth() + 1
				const date = d.getDate()
				// if(day.month == month && day.day == date + 3)
				// {
				// 	day.bottomInfo = '有优惠'
				// 	day.dot = true
				// }
				return day + "有优惠"

			},
			disableWeekends(date) {
				// 1. 将日期字符串转换为Date对象（兼容iOS）
				const dateObj = new Date(date.replace(/-/g, '/'));

				// 2. 获取星期几（0=周日，6=周六）
				const dayOfWeek = dateObj.getDay();

				// 3. 禁用所有周六(6)和周日(0)
				return dayOfWeek === 0 || dayOfWeek === 6;
			},

			getDot(date) {
				console.log(date)
				this.$request("TJDisTime", "GetPerCount", {
					TimeSpace: date,
					TJTestId: this.userInfo.TJTestId,
				}).then(res => {

					if (res.code == 1) {
						this.people = res.data
						// uni.hideLoading()
						// this.Organshow = true
						console.log(this.people)

					}


				})

			},


			change(e) {
				//待重做
				// 	console.log("》》》》》》》》》》》》》》》》》")	
				// 	console.log(e)
				// console.log(this.DotDate)
				// console.log("》》》》》》》》》》》》》》》》》")	
				// 	for (let i = 0; i < this.DotDate.length; i++) {
				// 		if (e.resule == this.DotDate[i].DisTime) {
				// 			uni.showToast({
				// 				title: '该日期已被预约请重新选择',
				// 				mask: true,
				// 				duration: 2000
				// 			})

				// 			return
				// 		}
				// 	}
				this.getDot(e.result)

				this.Date = e.result
			},
			getlist() {

				this.$request('TJCategory', 'GetTJTestDetail', {
					TJTestId: this.userInfo.TJTestId
				}).then(res => {
					console.log(res)
					if (res.code == 1) {

						this.userInfo.TJName = res.data.TJName
						this.userInfo.TJPrice = res.data.TJPrice
						this.userInfo.TJMainImg = res.data.TJMainImg



						uni.hideLoading();
					} else {
						uni.hideLoading();
						console.log("获取失败")
					}
					console.log(this.userInfo.TJName)
					console.log(this.userInfo.TJPrice)

				})

			},

			getDate() {
				this.$request("TJDisTime", "GetDisTime", {}).then(res => {

					if (res.code == 1) {
						this.DotDate = res.data
						console.log(this.DotDate)
						console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>")
						// uni.hideLoading()
						// this.Organshow = true
					}


				})


			},


			ComPay() {


				let user = this.userInfo
				this.$request('RegTJRecord', 'SubmitOrder', {
					TJChildId: this.userInfo.TJChildId,
					TJTestId: this.userInfo.TJTestId,
					TJRegDatetime: this.Date
				}).then(res => {
					console.log(res)
					if (res.code == 1) {
						console.log("提交成功了!!!!!!!!!")

						this.userInfo.OrderNo = res.data.ReqNo
						this.showPay = false
						this.showtishi3 = true


					} else {

						this.showtishi = true;
					}
				})
			},

			tomain() {

				uni.redirectTo({
					url: `/pages/MedicalExamination/Record/Record?current=${0}`,
					fail(error) {
						console.log(error)
					}
				})
				this.showtishi3 = false
			},




			pay() {

				var pattern = new RegExp("[\u4E00-\u9FA5]+");

				if (pattern.test(this.Date) || this.Date == '请选择日期' || this.Date == undefined) {

					this.showtishi2 = true;

					return

				} else {
					// uni.showLoading({
					// 	title: '订单提交中'
					// })


					this.showPay = true
				}



			},

			// paypay()
			// {
			// let user = this.userInfo
			// 				this.$request('RegTJRecord', 'SubmitOrder', {
			// 					TJChildId: this.userInfo.TJChildId,
			// 					TJTestId: this.userInfo.TJTestId,
			// 					TJRegDatetime: this.Date
			// 				}).then(res => {
			// 					console.log(res)
			// 					if (res.code == 1) {
			// 						console.log("提交成功了!!!!!!!!!")
			// 						this.showPay = true
			// 						this.userInfo.OrderNo = res.data.ReqNo
			// 						// let doctorinfor = false
			// 						// this.userInfo.TJChildId = ''
			// 						uni.hideLoading();
			// 						// uni.redirectTo({
			// 						// 	url: `/pages/MedicalExamination/MedicalExamination`,
			// 						// 	fail(error) {
			// 						// 		console.log(error)
			// 						// 	}
			// 						// })
			// 					} else {

			// 						this.showtishi=true;
			// 						console.log("登录失败了")
			// 						uni.hideLoading();
			// 						uni.showToast({
			// 							title: res.msg,
			// 							icon: 'none',
			// 							duration: 2000
			// 						});
			// 					}
			// 				})



			// },


			submit() {
				this.$refs.form1.validate(valid => {
					if (valid) {
						this.pay()
						console.log('验证通过');
					} else {
						console.log('验证失败');
					}
				});
			},
			cancel() {
				this.show = false
			},
			confirm(e) {
				this.sexs = e.value[0]
				this.userInfo.sex = e.value[0]
				this.show = false
			},
			addvisit() {
				console.log(this.userInfo)
				uni.showLoading({
					title: '提交中'
				})
				let user = this.userInfo
				this.$request('TJChildBase', 'AddchildBase', {
					TJChildId: this.userInfo.TJChildId,
					TJName: this.userInfo.TJName,
					TJIDCardNo: this.userInfo.TJIDCardNo,
					TJPhoneNo: this.userInfo.TJPhoneNo,
					TJPName: this.userInfo.TJPName,
					TJPIDCard: this.userInfo.TJPIDCard,
					TJKinderCode: this.userInfo.TJKinderCode,
					TJKinderName: this.selectKinder.current.label,
					TJGradeCode: this.userInfo.TJGradeCode,
					TJGradeName: this.selectGrade.current.label,
					TJClassName: this.userInfo.TJClassName,
					TJProvince: this.userInfo.TJProvince,
					TJCity: this.userInfo.TJCity,
					TJCounty: this.userInfo.TJCounty,
					TJAddress: this.userInfo.TJAddress,
					TJIllness: this.selectCase.current.label,
					TJOtherIll: this.userInfo.TJOtherIll,
					TJAllergies: this.userInfo.TJAllergies,
				}).then(res => {
					console.log("登录成功了!!!!!!!!!")
					if (res.code == 1) {
						let doctorinfor = false
						this.userInfo.TJChildId = ''
						uni.hideLoading();
						uni.redirectTo({
							url: `/pages/MedicalExamination/MedicalExamination`,
							fail(error) {
								console.log(error)
							}
						})
					} else {

						console.log("登录失败了")
						uni.hideLoading();
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			showToast(params) {
				this.$refs.uToast.show({
					...params,
					complete() {
						params.url && uni.navigateTo({
							url: params.url
						})
					}
				})
			},



			codeChange(text) {
				this.tips = text;
			},
			getCode() {

				if (this.userInfo.TJPhoneNo == "") {
					this.showToast(this.list)
					return
				}
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					setTimeout(() => {
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						uni.$u.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}, 2000);
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			// change(e) {
			// 	console.log('change', e);
			// }
		}
	}
</script>

<style>
	@import './Detail.css'
</style>